<?php
function classLoader($class) {
	$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
	$file = __DIR__ . '/' . $path . '.php';

	if(file_exists($file)) {
		require_once $file;
	}
}
spl_autoload_register('classLoader');
require_once('Qiniu/functions.php');
use Qiniu\Auth;
use Qiniu\Region;
use Qiniu\Storage\UploadManager;

class Qiniu {
	private $accessKey;
	private $secretKey;
	private $bucket;
	public $auth;
	public $token;

	function __construct() {
		$options = get_option('backup_qiniu');
		$options = unserialize($options);
		if($options) {
			$this->accessKey = $options['access_key'];
			$this->secretKey = $options['secret_key'];
			$this->bucket = $options['bucket_name'];
		}
	}
	private function verifyAK() {
		$region = new Region;
		$queryRegion = $region->queryRegion($this->accessKey, $this->bucket);
		if(is_array($queryRegion)) {
			list($ret, $err) = $queryRegion;
			return $err != null ? $err->message() : '';
		}
	}
	public function auth() {
		if(!$this->accessKey || !$this->secretKey || !$this->bucket) return 'API信息未完善';

		$err = $this->verifyAK();
		if($err) return $err;

		$this->auth = new Auth($this->accessKey, $this->secretKey);
	}
	public function token($save=null) {
		$this->token = $this->auth->uploadToken($this->bucket, $save);
	}
	public function upload($save, $file) {
		if(!file_exists($file)) return '文件不存在';
		$uploadMgr = new UploadManager();
		list($ret, $err) = $uploadMgr->putFile($this->token, $save, $file);
		return $err !== null ? $err->message() : '';
	}
	public function batchDelete($files) {
		$config = new \Qiniu\Config();
		$bucketManager = new \Qiniu\Storage\BucketManager($this->auth, $config);
		$ops = $bucketManager->buildBatchDelete($this->bucket, $files);
		list($ret, $err) = $bucketManager->batch($ops);
		return $err !== null ? $err->message() : '';
	}
	public function delete($file) {
		$config = new \Qiniu\Config();
		$bucketManager = new \Qiniu\Storage\BucketManager($this->auth, $config);
		list($ret, $err) = $bucketManager->delete($this->bucket, $file);
		return $err !== null ? $err->message() : '';
	}
}
?>